import {
    ab2hex,
} from '../../utils/util'
import {
    createBuffer,
    dataAnalysis,
    decimalToLittleEndian
} from './control'
var app = getApp()
let timer = null;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        show: false,
        showSetDY: false,
        showSetDl: false,
        showLoading: false,
        showSetSOC: false,
        showSetCloseDl: false,
        showLoading: false,
        devices: [
            // {name:'dAEA00000AGpGOWdAEA00000AGpGOWdAEA00000AGpGOW!@+_F#rHgF'},
            // {name:'GHIC-1134131!@+_F#rHgF',connectStatus:true},
        ], //查询到的蓝牙
        device: {
            // deviceId:'xx'
        }, //连接设备
        services: [], //服务
        serviceId: '',
        uuid: '',
        buleInfo: null,
        xqdy1: null,
        xqdl: null,
        soc: null,
        stopdl: null,
        version: '',
        batteryWidth: 80,
        showSetCar: false,
        buleNanme: "",
        setCar: {
            carNo: null,
            total: null,
            totalDY: null,
            type: null,
            singleDY: null,
            allowDY: null,
            allowDL: null,
            allowC: null
        },
        isAdmin: false,
        mtuTimer:false,
    },
    onClosedSet() {
        this.setData({
            showSetDY: false,
            showSetDl: false,
            showSetSOC: false,
            showSetCloseDl: false,
        })
    },
    handleOpenDY(v) {
        this.setData({
            showSetDY: true,
        })
    },
    handleOpenDL(v) {
        this.setData({
            showSetDl: true,
        })
    },
    handleOpenSOC(v) {
        this.setData({
            showSetSOC: true,
        })
    },
    handleOpenStopdl(v) {
        this.setData({
            showSetCloseDl: true,
        })
    },
    handleOpenSetCar() {
        this.setData({
            showSetCar: true
        })
    },
    onClosedSetCar() {
        this.setData({
            showSetCar: false
        })
    },
    onHide() {
        clearInterval(timer)
    },
    onShow() {
        if (this.data.device.deviceId) {
            // 发送请求控制信息 显示命令
            this.handleWrite(createBuffer(6, 0x90, 0x02, [0x10, 0x00]), '信息命令写入OK')
            this.handleWrite(createBuffer(6, 0x90, 0x02, [0x30, 0x00]), '版本命令写入ok')
            timer = setInterval(() => {
                this.handleWrite(createBuffer(6, 0x81, 0x01, [0x01, 0x7c]))
            }, 2000)
        }
        wx.getLocation({
            type: 'gcj02',
            success(res) {
                console.log(res)
            }
        })
        this.setData({
            isAdmin: wx.getStorageSync('isAdmin')
        })

    },
    onLoad(options) {

    },
    onClose() {
        if (this.data.device.name) {
            this.setData({
                show: false,
            })
        } else {
            this.setData({
                show: false,
                devices: [],
                services: [] //服务
            })
        }
    },
    handleChangeCarset(e) {
        this.data.setCar[e.target.dataset.type] = e.detail.value

        console.log(this.data.setCar)
    },
    convertToAscii(str) {
        var asciiArr = [];
        for (var i = 0; i < str.length; i++) {
            asciiArr.push(str.charCodeAt(i));
        }
        return asciiArr;
    },
    handleSetCar() {
        if(this.data.setCar.allowDL>100){
            wx.showToast({
              title: '最高允许充电电流最大100',
              icon:'none'
            })
            return
        }
        const data1 = this.convertToAscii(this.data.setCar.carNo)
        console.log('车辆序号', data1)
        const total = this.data.setCar.total
        const data2 = [decimalToLittleEndian(this.data.setCar.total * 10)[0], decimalToLittleEndian(this.data.setCar.total * 10)[1]]
        console.log('整体动力蓄电池额定容量', total, data2)


        const totalDY = this.data.setCar.totalDY
        const data3 = [decimalToLittleEndian(this.data.setCar.totalDY * 10)[0], decimalToLittleEndian(this.data.setCar.totalDY * 10)[1]]
        console.log('整体动力蓄电池额定总电压', totalDY, data3)

        const type = this.data.setCar.type
        const data4 = parseInt(type)
        console.log('电池类型', type, data4)


        const singleDY = this.data.setCar.singleDY
        const data5 = [decimalToLittleEndian(this.data.setCar.singleDY * 100)[0], decimalToLittleEndian(this.data.setCar.singleDY * 100)[1]]
        console.log('单体动力蓄电池最高允许充电电压', singleDY, data5)

        const allowDY = this.data.setCar.allowDY
        const data6 = [decimalToLittleEndian(this.data.setCar.allowDY * 10)[0], decimalToLittleEndian(this.data.setCar.allowDY * 10)[1]]
        console.log('最高允许充电总电压', allowDY, data6)

        const allowDL = this.data.setCar.allowDL
        const data7 = [decimalToLittleEndian((this.data.setCar.allowDL * 10) + 4000)[0], decimalToLittleEndian((this.data.setCar.allowDL * 10) + 4000)[1]]
        console.log('最高允许充电电流', allowDL, data7)

        const allowC = this.data.setCar.allowC
        const data8 = parseInt(allowC) + 50
        console.log('最高允许充电温度', allowC, data8)

        const dataAll = data1.concat(data2).concat(data3).concat(data4).concat(data5).concat(data6).concat(data7).concat(data8)
        console.log(dataAll, '总数居')
        this.handleWrite(createBuffer(33, 0xA2, 29, dataAll), '设置命令写入OK')

    },
    handleOpen() {
        if (!wx.getStorageSync('token')) {
            wx.showModal({
                title: '提示',
                content: '请登录后操作设备',
                complete: (res) => {
                    if (res.cancel) {

                    }

                    if (res.confirm) {
                        wx.navigateTo({
                            url: '/pages/login/login',
                        })
                    }
                }
            })
            return
        }
        this.setData({
            show: true,
        })
        this.openBluetoothAdapter()
    },
    // 第一步初始化蓝牙
    openBluetoothAdapter() {
        const _this = this
        wx.openBluetoothAdapter({
            success: function (res) {
                console.log('第一步，蓝牙初始化成功', res)
                //开始搜索附近蓝牙
                _this.startBluetoothDevicesDiscovery()
            },
            fail: function (res) {
                console.log("第一步、蓝牙初始化失败", res);
                wx.showToast({
                    title: `蓝牙初始化失败${res.errCode}`,
                    icon: 'none'
                })
            }
        })
    },
    // 第二步 开始搜索附近的蓝牙设备
    startBluetoothDevicesDiscovery() {
        const _this = this
        this.setData({
            showLoading: true
        })
        wx.startBluetoothDevicesDiscovery({
            services: [], //搜索目标设备的服务
            allowDuplicatesKey: false, //搜索结果是否允许重复
            success: function (res) {
                console.log(res, '搜索蓝牙设备成功')
                _this.onBluetoothDeviceFound()
            },
            fail: function (err) {
                console.log(err, '搜索蓝牙设备失败')
                wx.showToast({
                    title: res.errCode + '搜索蓝牙失败',
                })
            }
        })
    },
    // 第三步 监听发现附近的蓝牙设备
    onBluetoothDeviceFound() {
        const _this = this
        wx.onBluetoothDeviceFound((res) => {
            res.devices.forEach(device => {
                if (device.name.indexOf('GHIC') != -1) {
                    device.isShowBtn = true
                }
                if (!device.name && !device.localName) {
                    return
                }
                console.log("发现的蓝牙设备", device)
                var isHave = this.data.devices.find((obj) => {
                    return device.deviceId == obj.deviceId
                })
                if (isHave !== undefined) {
                    console.log('蓝牙已存在')
                } else {
                    // 蓝牙不存在加入蓝牙列表
                    device.connectStatus = false
                    if (device.name.indexOf('GHIC') != -1) {
                        device.isShowBtn = true
                    }
                    this.data.devices.push(device)
                    this.setData({
                        devices: this.data.devices
                    })
                }
            })
        })
    },
    // 第四步、 建立连接
    connectDevice: function (e) {
        const device = e.currentTarget.dataset.device
        this.setData({
            device: device
        })
        const _this = this
        wx.createBLEConnection({
            deviceId: device.deviceId,
            success: (res) => {
                console.log('createBLEConnection success 已链接设备', res)
                _this.data.devices.forEach(el => {
                    if (el.deviceId == device.deviceId) {
                        el.connectStatus = true
                    }
                })
                _this.setData({
                    devices: _this.data.devices
                })
                wx.setStorageSync('deviceId', device.deviceId)
                wx.showToast({
                    title: '蓝牙连接成功',
                    icon: 'success',
                    duration: 3000
                })


                if (wx.getStorageSync('isUpload')) {
                    wx.showModal({
                        title: '蓝牙已连接',
                        content: '如需升级请前往升级页面继续获取服务端版本升级',
                        complete: (res) => {
                            if (res.cancel) {

                            }

                            if (res.confirm) {

                            }
                        }
                    })
                }

                const title = device.name.substring(0, 11)
                wx.setNavigationBarTitle({
                    title: title,
                })
                // 修改mtu

                wx.setBLEMTU({
                    deviceId: device.deviceId,
                    mtu: 150,
                    success: res => {
                        console.log('mtu修改成功')
                        wx.showToast({
                            title: 'mtu修改成功',
                        })
                    },
                    fail: (err) => {
                        console.log('mtu修改失败', err)
                        wx.showToast({
                            title: 'mtu修改失败',
                            icon:'error'
                        })
                        _this.setAndroidMTU()
                    }
                })
                // 停止搜索
                _this.stopBluetoothDevicesDiscovery()
                _this.setData({
                    show: false
                })
                // 获取服务
                _this.getBLEDeviceServices()
                _this.setData({
                    showLoading: false
                })
            },
            fail: (res) => {
                wx.showToast({
                    title: '蓝牙连接失败',
                    icon: 'none'
                })
            }
        })

        wx.onBLEConnectionStateChange(function (res) {
            console.log(`蓝牙设备 ${res.deviceId} 连接状态变化：${res.connected}`);
            if (res.connected) {
                // 蓝牙设备已连接
                // 执行相关操作
            } else {
                // 蓝牙设备已断开连接
                // 执行相关操作

                wx.showModal({
                    title: '蓝牙已断开',
                    content: '请重新搜索蓝牙连接后，进行后续操作',
                    complete: (res) => {
                        if (res.cancel) {}
                        if (res.confirm) {}
                    }
                })

                wx.setNavigationBarTitle({
                    title: '参数设置',
                })
                _this.setData({
                    show: false,
                    devices: [], //查询到的蓝牙
                    device: {}, //连接设备
                    services: [], //服务
                    buleInfo: null
                })
                clearInterval(timer)
                console.log(_this.data)
            }
        });

    },
    setAndroidMTU() {
        let _ = this;
        console.log('处理安卓协商低功耗最大传输单元失败的方法')
        _.mtuTimer = setInterval(() => {
            console.log('开始循环设置MTU值')
            wx.setBLEMTU({
                deviceId: _.device.deviceId, 
                mtu: 150,
                success(res) {
                    console.log('设置mtu成功')
                    wx.showToast({
                      title: '设置mtu成功',
                      icon:'success'
                    })
                },
                fail(err) {
                    console.error(err)
                },
                complete() {
                    wx.getBLEMTU({
                        deviceId: _.device.deviceId,
                        writeType: 'write',
                        success(res) {
                            clearInterval(_.mtuTimer)
                            _.mtuTimer = null;
                        }
                    })
                }
            })
        }, 1500)
    },
    // 获取蓝牙外围设备的服务
    getBLEDeviceServices() {
        const _this = this
        wx.getBLEDeviceServices({
            deviceId: this.data.device.deviceId,
            success: (res => {
                console.log(res.services, '蓝牙上的所有服务')
                const arr = []
                // for (let i = 0; i < res.services.length; i++) {
                //   if (res.services[i].isPrimary) {
                //     // 可根据具体业务需要，选择一个主服务进行通信
                //     arr.push(res.services[i])
                //     _this.setData({
                //       services: arr
                //     })
                //     console.log(_this.data.services, '服务-=================')
                //     _this.getBLEDeviceCharacteristics(_this.data.device.deviceId, res.services[i].uuid)
                //   }
                // }
                // 选择第一个服务通讯
                if (res.services && res.services[0] && res.services[0].isPrimary) {
                    _this.getBLEDeviceCharacteristics(_this.data.device.deviceId, res.services[0].uuid)
                }
            })
        })
    },
    // 读写服务的特征值
    getBLEDeviceCharacteristics(deviceId, serviceId) {
        const _this = this
        wx.getBLEDeviceCharacteristics({
            deviceId, // 搜索到设备的 deviceId
            serviceId, // 上一步中找到的某个服务
            success: (res) => {
                console.log(res.characteristics, '----------characteristics')
                for (let i = 0; i < res.characteristics.length; i++) {
                    let item = res.characteristics[i]
                    if (item.properties.write) { // 该特征值可写
                        _this.setData({
                            serviceId: serviceId,
                            uuid: item.uuid
                        })
                        wx.setStorageSync('serviceId', serviceId)
                        wx.setStorageSync('uuid', item.uuid)
                        // 蓝牙 APP 启动，发送连接命令
                        _this.handleWrite(createBuffer(5, 0x81, 0x01, [0x01]), '连接命令写入OK')
                        // 发送请求控制信息 显示命令 参数
                        _this.handleWrite(createBuffer(6, 0x90, 0x02, [0x10, 0x00]), '信息命令写入OK')
                        // 发送请求控制信息 显示命令 版本
                        _this.handleWrite(createBuffer(6, 0x90, 0x02, [0x30, 0x00]), '版本命令写入OK')
                        // 每间隔2s发送
                        timer = setInterval(() => {
                            _this.handleWrite(createBuffer(6, 0x81, 0x01, [0x01, 0x7c]))
                        }, 2000)
                    }
                    if (item.properties.read) { // 改特征值可读
                        wx.readBLECharacteristicValue({
                            deviceId,
                            serviceId,
                            characteristicId: item.uuid,
                            success: (res) => {
                                console.log(res, item.uuid, '读取数据成功-----')
                                wx.showToast({
                                    title: '读取数据成功!',
                                    icon: 'success'
                                })
                            },
                            fail: (res) => {
                                wx.showToast({
                                    title: '读取数据失败!',
                                    icon: 'error'
                                })
                                console.log(res, item.uuid, '读取数据失败')
                            }
                        })
                    }
                    if (item.properties.notify || item.properties.indicate) {
                        // 必须先启用 wx.notifyBLECharacteristicValueChange 才能监听到设备 onBLECharacteristicValueChange 事件
                        wx.notifyBLECharacteristicValueChange({
                            deviceId,
                            serviceId,
                            characteristicId: item.uuid,
                            state: true,
                            type: "notification",
                            success: (res) => {
                                console.log(res, "notify创建连接")
                            }
                        })
                    }
                }
            }
        })
        // 操作之前先监听，保证第一时间获取数据
        wx.onBLECharacteristicValueChange((result) => {
            let ab2hexdata = ab2hex(result.value)
            console.log(dataAnalysis(ab2hexdata), '监听到了蓝牙参数页面----------------')
            if (ab2hexdata) {
                if (dataAnalysis(ab2hexdata).type == 1) {
                    _this.setData({
                        buleInfo: dataAnalysis(ab2hexdata)
                    })
                    wx.setStorageSync('clxlh', dataAnalysis(ab2hexdata).clxlh)
                }
            }

            // 使用完成后在合适的时机断开连接和关闭蓝牙适配器
            // wx.closeBLEConnection({
            //   deviceId,
            // })
            // wx.closeBluetoothAdapter({})
        })
    },
    //  停止搜索
    stopBluetoothDevicesDiscovery() {
        wx.stopBluetoothDevicesDiscovery({
            success: function (res) {
                console.log('停止搜索成功');
            },
            fail: function (res) {
                console.log('停止搜索失败');
            }
        });
    },
    disconnectDevice(e) {
        const device = e.currentTarget.dataset.device
        const _this = this
        wx.closeBLEConnection({
            deviceId: device.deviceId,
            success: (res) => {
                console.log(res, '断开成功')
                clearInterval(timer)
                _this.data.devices.forEach(el => {
                    if (el.deviceId == device.deviceId) {
                        el.connectStatus = false
                    }
                })
                _this.handleClear()
                _this.setData({
                    show: false,
                    devices: [], //查询到的蓝牙
                    device: {}, //连接设备
                    services: [], //服务
                    buleInfo: null
                })
                wx.setNavigationBarTitle({
                    title: '参数设置',
                })
                wx.showToast({
                    title: '已断开，请重新搜索',
                    icon: 'error'
                })
            },
            fail: (err) => {
                wx.showToast({
                    title: '断开失败',
                    icon: 'error'
                })
                console.log(err, '断开失败')
            }
        })
        _this
        // wx.closeBluetoothAdapter({})
    },
    // 写数据
    handleWrite(value, text) {
        wx.writeBLECharacteristicValue({
            deviceId: this.data.device.deviceId,
            serviceId: this.data.serviceId,
            characteristicId: this.data.uuid,
            value,
            success: (res) => {
                if (text) {
                    wx.showToast({
                        title: text,
                        icon: 'none'
                    })
                }
                console.log(res, this.data.device.deviceId, this.data.uuid, this.data.serviceId, '写入数据成功=========')
                // 发送请求控制信息 显示命令
                // this.handleGetInfo(createBuffer(6, 0x90, 0x02, [0x10, 0x00]))
                this.handleWathc()
            },
            fail: (res) => {
                // if (wx.getStorageSync('isUpload')) {
                //   wx.showModal({
                //     title: '提示',
                //     content: '请检查蓝牙连接状态，或断开后重新搜索连接蓝牙',
                //     complete: (res) => {
                //       if (res.cancel) {}

                //       if (res.confirm) {}
                //     }
                //   })
                // }

                wx.showToast({
                    title: '命令写入失败',
                    icon: 'error'
                })
                console.log(res, this.data.uuid, this.data.serviceId, '写入数据失败')
            }
        })
    },
    handleGetInfo(value) {
        wx.writeBLECharacteristicValue({
            deviceId: this.data.device.deviceId,
            serviceId: this.data.serviceId,
            characteristicId: this.data.uuid,
            value,
            success: (res) => {
                wx.showToast({
                    title: '指令发送完成',
                    icon: 'none'
                })
                console.log(res, this.data.uuid, this.data.serviceId, '写入数据成功=========')
                this.handleWathc()
            },
            fail: (res) => {
                // if (wx.getStorageSync('isUpload')) {
                //   wx.showModal({
                //     title: '提示',
                //     content: '请检查蓝牙连接状态，或断开后重新搜索连接蓝牙',
                //     complete: (res) => {
                //       if (res.cancel) {}

                //       if (res.confirm) {}
                //     }
                //   })
                // }
                wx.showToast({
                    title: '写入数据失败',
                    icon: 'error'
                })
                console.log(res, this.data.uuid, this.data.serviceId, '写入数据失败')
            }
        })
    },
    handleChangeDY1(e) {
        this.setData({
            xqdy1: e.detail.value
        })
    },
    // 设置需求电压
    handleSetDY() {
        if (this.data.xqdy1 >= 780) {
            wx.showToast({
                title: '请设置780以下',
                icon: 'error'
            })
            return
        }
        console.log(this.data.xqdy1 * 10)
        console.log(decimalToLittleEndian(this.data.xqdy1 * 10))
        this.handleWrite(createBuffer(7, 0xA1, 0x03, [0x01, decimalToLittleEndian(this.data.xqdy1 * 10)[0], decimalToLittleEndian(this.data.xqdy1 * 10)[1]]), '电压命令写入OK')
    },
    hanleChangeDL(e) {
        this.setData({
            xqdl: e.detail.value
        })
    },

    // 设置需求电流
    handleSetDL() {
        if (this.data.xqdl >= 100) {
            wx.showToast({
                title: '请设置100以下',
                icon: 'error'
            })
            return
        }
        console.log(this.data.xqdl * 10)
        console.log(decimalToLittleEndian(this.data.xqdl * 10))
        this.handleWrite(createBuffer(7, 0xA1, 0x03, [0x02, decimalToLittleEndian(this.data.xqdl * 10)[0], decimalToLittleEndian(this.data.xqdl * 10)[1]]), '电流命令写入OK')
    },
    handlechangeSoc(e) {
        this.setData({
            soc: e.detail.value
        })
    },
    // 设置soc
    handleSetSoc() {
        if (this.data.soc > 100) {
            wx.showToast({
                title: '请设置100以下',
                icon: 'error'
            })
            return
        }
        console.log(this.data.soc * 10)
        console.log(decimalToLittleEndian(this.data.soc * 10))
        this.handleWrite(createBuffer(7, 0xA1, 0x03, [0x03, decimalToLittleEndian(this.data.soc * 10)[0], decimalToLittleEndian(this.data.soc * 10)[1]]), 'soc命令写入OK')
    },
    // 停止充电
    handleStop() {
        this.handleWrite(createBuffer(7, 0xA1, 0x03, [0x04, 0x00, 0x00]), '停止命令写入OK')
    },
    // 复位
    handlefw() {
        this.handleWrite(createBuffer(7, 0xA1, 0x03, [0x05, 0x00, 0x00]), '复位命令写入OK')
    },
    handlechangeDL(e) {
        this.setData({
            stopdl: e.detail.value
        })
    },
    // 关机电流
    handleSetStopdl() {
        console.log(this.data.stopdl * 10)
        console.log(decimalToLittleEndian(this.data.stopdl * 10))
        this.handleWrite(createBuffer(7, 0xA1, 0x03, [0x06, decimalToLittleEndian(this.data.stopdl * 10)[0], decimalToLittleEndian(this.data.stopdl * 10)[1]]), '关机电流写入OK')
    },
    handleWathc() {
        const _this = this
        wx.notifyBLECharacteristicValueChange({
            deviceId: this.data.device.deviceId,
            serviceId: this.data.serviceId,
            characteristicId: this.data.uuid,
            state: true,
            type: "notification",
            success: (res) => {
                console.log(res, "notify创建连接")
            }
        })
        // 操作之前先监听，保证第一时间获取数据
        wx.onBLECharacteristicValueChange((result) => {
            let ab2hexdata = ab2hex(result.value)
            console.log(dataAnalysis(ab2hexdata), '监听到了蓝牙参数页面=======================')
            if (ab2hexdata) {
                if (dataAnalysis(ab2hexdata).type == 1) {
                    _this.setData({
                        buleInfo: dataAnalysis(ab2hexdata)
                    })
                }
                if (dataAnalysis(ab2hexdata).type == 2) {
                    // 有版本存下版本
                    console.log(dataAnalysis(ab2hexdata).version, '获取版本信息')
                    if (dataAnalysis(ab2hexdata).version) {
                        wx.setStorageSync('version', dataAnalysis(ab2hexdata).version)
                        _this.setData({
                            version: dataAnalysis(ab2hexdata).version
                        })
                    } else {
                        // 没有版本
                        _this.setData({
                            version: wx.getStorageSync('version')
                        })
                    }


                }
            }

        })
    },
    handleClear() {
        this.setData({

        })
    },
    handleOpenSetName() {
        this.setData({
            showSetName: true,
            buleNanme: this.data.buleInfo ? this.data.buleInfo.clxlh.substring(11, 17) : '未获取到车辆序列号'
        })
    },
    onClosedSetName() {
        this.setData({
            showSetName: false
        })
    },
    handlechangeName(e) {
        this.setData({
            buleNanme: e.detail.value
        })
    },
    padAndConvertToAscii(str) {
        let paddedStr = str.padEnd(20, '0'); // 在字符串末尾添加'0'直到长度为20
        let asciiCodes = paddedStr.split('').map(char => char.charCodeAt(0)); // 转换每个字符为ASCII码
        return asciiCodes; // 用逗号连接ASCII码形成字符串
    },
    handleSetBlueName() {
        console.log(this.data.buleNanme)
        console.log(this.padAndConvertToAscii('GHIC-' + this.data.buleNanme))
        this.handleWrite(createBuffer(24, 0xA3, 20, this.padAndConvertToAscii('GHIC-' + this.data.buleNanme)), '蓝牙名称写入OK')
    }
})